package com.cruise.h5.util;

import com.cruise.common.web.ex.BizException;
import com.cruise.common.web.result.Result;
import com.cruise.h5.pojo.vo.UploadFileVO;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author ：Cruise
 * @version ：1.0
 * @Calss ：UploadFilesUtil
 * @Description ：TODO
 * @date ：2021/4/12 下午11:09
 **/
public class UploadFilesUtil {

    /**
     * UPLOAD_URL 带压缩的文件目录和文件上传路径
     */
    public static String UPLOAD_URL;
    /**
     * 文件的访问路径（基于外置的tomcat图床）
     */
    public static  String DOWNLOAD_URL;

    private static Date data = new Date();
    private static SimpleDateFormat adf = new SimpleDateFormat("/yyyy/MM/dd");
    private static String format = adf.format(data);

    // 读取yml里的属性值
    static {
        YamlPropertiesFactoryBean yamlMapFactoryBean = new YamlPropertiesFactoryBean();
        //可以加载多个yml文件
        yamlMapFactoryBean.setResources(new ClassPathResource("bootstrap.yml"));
        Properties properties = yamlMapFactoryBean.getObject();
        //获取yml里的路径参数
        if (properties != null) {
            UPLOAD_URL = properties.getProperty("upload-url")+ File.separator + format + File.separator;
            DOWNLOAD_URL = properties.getProperty("download-url")+ File.separator + format + File.separator;
            if (UPLOAD_URL == null || "".equals(UPLOAD_URL)){
                throw new BizException("上传路径为空");
            }
            if (DOWNLOAD_URL == null || "".equals(DOWNLOAD_URL)){
                throw new BizException("访问路径为空");
            }
        }else {
            throw new BizException("找不到名为bootstrap.yml配置文件");
        }
        //上传路径
        File targetFile = new File(UPLOAD_URL);
        //如果路径不存在就创建
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
    }
    /**
     * TODO: 文件上传（可一次上传多个文件也可以一次上传一个文件）
     * @param files 上传的文件
     * @return com.wb.srpingboot.demoz.utils.Result
     */
    public static Result uploads(MultipartFile[] files){
        if(files.length > 0 && !(files[0].isEmpty())){
            //创建流
            FileInputStream fis = null;
            FileOutputStream fos = null;
            //创建通道
            FileChannel inChannel = null;
            FileChannel outChannel = null;
            String newName;
            List<String> imgName = new ArrayList<>();
            try {
                for (MultipartFile file : files) {
                    String realName = file.getOriginalFilename();
                    //初始化文件新名字
                    if (realName != null && realName != "") {
                        //获取文件后缀
                        String suffixName = realName.substring(realName.lastIndexOf("."));
                        //生成新名字
                        newName = UUID.randomUUID().toString().replaceAll("-", "") + suffixName;
                    } else {
                        return Result.failed("文件名不可为空");
                    }

                    fis = (FileInputStream) file.getInputStream();
                    //开始上传
                    fos = new FileOutputStream(UPLOAD_URL + File.separator + format + File.separator + newName);
                    //通道间传输
                    inChannel = fis.getChannel();
                    outChannel = fos.getChannel();
                    //上传
                    inChannel.transferTo(0, inChannel.size(), outChannel);
                    imgName.add(newName);
                }
                //打成压缩包
                //toCompress("haha");
            }catch (IOException e) {
                return Result.failed("文件上传路径错误");
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                //关闭资源
                try {
                    if (fis != null) {
                        fis.close();
                    }
                    if (fos != null) {
                        fos.close();
                    }
                    if (inChannel != null) {
                        inChannel.close();
                    }
                    if (outChannel != null) {
                        outChannel.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return Result.success(imgName);
        }
        return Result.failed("请选择文件");
    }

    /**
     * 文件上传方法（单个）
     */
    public static Result uploading(MultipartFile file) {

        UploadFileVO uploadFileBO = new UploadFileVO();
        //获取文件名
        String realName = file.getOriginalFilename();
        uploadFileBO.setFileName(realName);
        String newName = null;
        if(realName != null && realName != ""){
            //获取文件后缀
            String suffixName = realName.substring(realName.lastIndexOf("."));
            //生成新名字
            newName = UUID.randomUUID().toString().replaceAll("-", "")+suffixName;
            uploadFileBO.setFileUrl(format + File.separator + newName);
        }else {
            return Result.failed("文件名不可为空");
        }
        //创建流
        FileInputStream fis = null;
        FileOutputStream fos = null;
        //创建通道
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        try {
            fis = (FileInputStream)file.getInputStream();
            //开始上传
            fos = new FileOutputStream(UPLOAD_URL + newName);
            //通道间传输
            inChannel = fis.getChannel();
            outChannel = fos.getChannel();
            //上传
            inChannel.transferTo(0,inChannel.size(),outChannel);

        }catch (IOException e){
            return Result.failed("文件上传路径错误");
        }finally {
            //关闭资源
            try {
                if (fis != null) {
                    fis.close();
                }
                if (fos != null) {
                    fos.close();
                }
                if (inChannel != null) {
                    inChannel.close();
                }
                if (outChannel != null) {
                    outChannel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return Result.success(uploadFileBO);

    }

    /**
     * base64转图片
     * @param base64str base64码
     * @return
     */
    public static UploadFileVO generateImage(String base64str) {

        UploadFileVO uploadFileBO = new UploadFileVO();
        String s = base64str.split(",")[1];
        String aa  = base64str.split(",")[0].split(";")[0];
        String filenameSuffix = "." + aa.substring(aa.indexOf("/")+1);
        //拼接路径
        String newName = UUID.randomUUID().toString().replaceAll("-", "")+filenameSuffix;
        uploadFileBO.setFileName(newName);
        uploadFileBO.setFileUrl(format + File.separator + newName);
        //对字节数组字符串进行Base64解码并生成图片
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            //Base64解码
            byte[] b = decoder.decodeBuffer(s);
            for (int i = 0; i < b.length; ++i) {
                //调整异常数据
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            //生成jpeg图片
            OutputStream out = new FileOutputStream(UPLOAD_URL + newName);
            out.write(b);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return uploadFileBO;

    }
}
